﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Linq;
using SuperSimpleWebshop.Common;
using SuperSimpleWebshop.Domain;
using SuperSimpleWebshop.Domain.Interfaces;
using umbraco;
using umbraco.BusinessLogic;

namespace SuperSimpleWebshop.Payment.MultiSafePay
{
    public class MultiSafePayPaymentResponseHandler : MultiSafePayPaymentBase, IPaymentResponseHandler
    {
        #region IPaymentResponseHandler Members
        public string HandlePaymentResponse()
        {
            string transactionId = library.Request("transactionid");
            var order = this.OrderRepository.GetOrderByPaymentTransactionId(transactionId);
            var helper = new PaymentConfigHelper(order.OrderInfo.PaymentInfo.PaymentProviderNodeName);

            var statusRequest = new StatusRequest
            {
                AccountId = long.Parse(helper.Settings["accountId"]),
                TransactionId = transactionId,
                SiteId = long.Parse(helper.Settings["siteId"]),
                SiteSecureId = long.Parse(helper.Settings["siteSecureId"])
            };

            string apiURL = string.Empty;

            if (helper.TestModeEnabled)
            {
                apiURL = helper.Settings["testURL"];
            }
            else
            {
                apiURL = helper.Settings["url"];
            }

            try
            {
                var httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(apiURL);
                httpWebRequest.Method = "POST";
                httpWebRequest.ContentLength = Encoding.UTF8.GetByteCount(statusRequest.GetXML());
                httpWebRequest.ContentType = "application/x-www-form-urlencoded";

                var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream());
                streamWriter.Write(statusRequest.GetXML());
                streamWriter.Close();

                var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                var streamReader = new StreamReader(httpWebResponse.GetResponseStream());
                var xmlDoc = XDocument.Parse(streamReader.ReadToEnd());
                var ewallet = xmlDoc.Root.Element("ewallet");
                var status = ewallet.Element("status").Value;
                Log.Add(LogTypes.Debug, 0, "status: " + status);
                //if (order.OrderInfo.Status == OrderStatus.Ready_for_Dispatch && status == "completed")
                //{
                //    return null;
                //}

                order.OrderInfo.Status = OrderStatus.Waiting_for_Payment;

                //– completed: succesvol voltooid
                //– initialized: aangemaakt, maar nog niet voltooid
                //– uncleared: aangemaakt, maar nog niet vrijgesteld (credit cards)
                //– void: geannuleerd
                //– declined: afgewezen
                //– refunded: terugbetaald
                //– expired: verlopen

                if (status == "completed")
                {
                    order.OrderInfo.Status = OrderStatus.Ready_for_Dispatch;
                }
                if (status == "uncleared")
                {
                    order.OrderInfo.Status = OrderStatus.Waiting_for_Payment;
                }
                if (status == "declined")
                {
                    order.OrderInfo.Status = OrderStatus.Payment_Failed;
                    order.OrderInfo.PaymentInfo.PaymentErrorMessage = status;
                }
                if (status == "expired")
                {
                    order.OrderInfo.Status = OrderStatus.Payment_Failed;
                    order.OrderInfo.PaymentInfo.PaymentErrorMessage = status;
                }
                if (status == "void")
                {
                    order.OrderInfo.Status = OrderStatus.Payment_Failed;
                    order.OrderInfo.PaymentInfo.PaymentErrorMessage = status;
                }

                order.Save();
            }
            catch (Exception ex)
            {
                Log.Add(LogTypes.Error, 0, "MultiSafePayPaymentResponseHandler.HandlePaymentResponse: " + ex.ToString());
            }

            return null;
        }
        #endregion
    }
}
